import 'package:flutter/material.dart';
import 'package:flutter_easylogger/flutter_logger.dart';
import 'package:get/get.dart';
import 'package:dio/dio.dart';

import '../../config/router_page_name.dart';
import '../../http/http_service.dart';
import '../../widgets/finger_print_scan_dialog.dart';

class RegisterAccountLogic extends GetxController {
  TextEditingController emailController = TextEditingController();
  TextEditingController accountController = TextEditingController();
  TextEditingController passwordController = TextEditingController();
  TextEditingController confirmPasswordController = TextEditingController();

  final httpService = HttpService();
  final formKey = GlobalKey<FormState>();

  Future<void> handleRegistration() async {
    if (!_validateForm()) return;

    final animationFuture = Get.dialog(
      const FingerPrintScanDialog(),
      barrierColor: Colors.black38,
      barrierDismissible: false,
    );

    final registrationFuture = _performRegistration();

    // 等待动画和请求同时完成
    await Future.wait([animationFuture, registrationFuture]);
  }

  bool _validateForm() {
    // 检查所有字段是否为空
    if (emailController.text.isEmpty) {
      Get.snackbar("错误", "邮箱不能为空");
      return false;
    }

    if (accountController.text.isEmpty) {
      Get.snackbar("错误", "账号不能为空");
      return false;
    }

    if (passwordController.text.isEmpty) {
      Get.snackbar("错误", "密码不能为空");
      return false;
    }

    if (confirmPasswordController.text.isEmpty) {
      Get.snackbar("错误", "确认密码不能为空");
      return false;
    }

    // 验证邮箱格式
    final emailRegExp = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$');
    if (!emailRegExp.hasMatch(emailController.text)) {
      Get.snackbar("错误", "请输入有效的邮箱地址");
      return false;
    }

    // 验证账号长度
    if (accountController.text.length <= 5) {
      Get.snackbar("错误", "账号长度必须大于5个字符");
      return false;
    }

    // 验证密码长度和格式
    if (passwordController.text.length <= 6) {
      Get.snackbar("错误", "密码长度必须大于6个字符");
      return false;
    }

    // 验证密码只包含数字和字母
    final passwordRegExp = RegExp(r'^[a-zA-Z0-9]+$');
    if (!passwordRegExp.hasMatch(passwordController.text)) {
      Get.snackbar("错误", "密码只能包含数字和字母");
      return false;
    }

    // 验证两次输入的密码是否一致
    if (passwordController.text != confirmPasswordController.text) {
      Get.snackbar("错误", "两次输入的密码不一致");
      return false;
    }

    return true;
  }

  Future<void> _performRegistration() async {
    final response = await httpService.post('/user/register', data: {
      'email': emailController.text,
      'username': accountController.text,
      'password': passwordController.text,
    });

    Get.back(); // 关闭加载动画

    if (response.statusCode == 200) {
      Logger.i('注册成功');
      Get.snackbar("成功", "注册成功");

      Get.offAllNamed(
          RouterPageName.loginAccountPage,
          arguments: {
            'username': accountController.text,
            'password': passwordController.text,
          }
      );
    } else {
      var errorData = response.data;
      String errorMessage = "注册失败，请重试";

      if (errorData is Map<String, dynamic>) {
        errorMessage = errorData['message'] ?? errorData['error'] ?? errorMessage;
      } else if (errorData is String) {
        errorMessage = errorData;
      }

      Logger.e('注册失败: $errorMessage');
      Get.snackbar("错误", errorMessage);
    }
  }

  @override
  void onClose() {
    emailController.dispose();
    accountController.dispose();
    passwordController.dispose();
    confirmPasswordController.dispose();
    super.onClose();
  }
}